package com.zy.stack;


import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


/**
 * Created by zhaoyi on 2019/7/22
 * 逆波兰表达式求值
 *  运算符包括 +, -, *, /
 *  https://leetcode-cn.com/explore/learn/card/queue-stack/218/stack-last-in-first-out-data-structure/880/
 */
public class StackEvalRPN {

    /**
     * 应该拓展下中坠转后缀表达式的方式
     * 不过也已经是前人总结好的了固定方式了
     * @param tokens
     * @return
     */
    public int evalRPN(String[] tokens) {
        Stack<Integer> value = new Stack<>();
        List<String> opers = new ArrayList();
        opers.add("+");
        opers.add("-");
        opers.add("*");
        opers.add("/");

        for (String token : tokens) {
            //boolean isNum = Pattern.matches("\\d+", token);
            boolean isNum = !opers.contains(token);
            if(isNum){
                value.push(Integer.valueOf(token));
            }else {
                Integer top = value.pop();
                Integer senend = value.pop();
                value.push(math(senend,top,token));
            }
        }
        return value.peek();
    }

    private int math(Integer senend, Integer top, String oper) {

        if("+".equals(oper)){
            return senend+top;
        }else if("-".equals(oper)){
            return senend - top;
        }else if("*".equals(oper)){
            return Math.multiplyExact(senend,top);
        }else {
            return senend/top;
        }
    }


}
